<?php $this->headScript()->appendFile($this->JS_PATH . 'quotation.js'); ?>
<div id="MainContent">
    <div>
        <div class="pageerrorcontainer-validator jscript-error-container">
            <div class="error-iterator"></div>
        </div>
    </div>

    <?php if ($this->succesMessage != ""): ?>
        <div class='pagemcontainer'>
            <p class='pagemessage'>
                <img src="<?php echo $this->IMAGE_PATH; ?>icons/system/accept.gif" class="systemicon" alt="Success" title="Success" />
                <label class='errorlabel'><?php echo $this->succesMessage; ?></label>
            </p>
        </div>
    <?php endif; ?>			

    <?php if (count($this->errorMessageArray) > 0): ?>
        <div class="pageerrorcontainer">
            <?php foreach ($this->errorMessageArray as $erroValue): ?>
                <div class="pageoverflow">
                    <img src="<?php echo $this->IMAGE_PATH; ?>icons/system/stop.gif" class="systemicon" alt="Error" title="Error" />
                    <label class="errorlabel"><?php echo $erroValue; ?></label>
                </div>
            <?php endforeach; ?>				
        </div>
    <?php endif; ?>
</div>

<div class="clearb">&nbsp;</div>
<div id="quotation"></div>
<div class="pagecontainer pageoverflow">
    <div class="pageheader">
        <?php echo $this->mode;?> Quotation
    </div>
    <div style="clear: both;"></div>
    <form id="quotation-form" name="quotation-form"  enctype="multipart/form-data"  action="" method="post">
        <input type="hidden" readonly size="60" id="item_count" value="<?php echo count($this->quotationReference);?>" name="item_count"/>
        <input type="hidden" readonly size="60" id="hdn_delete_qnrids" value="" name="hdn_delete_qnrids"/>
        <div id="page_content">
            <div class="pageoverflow display-none">
                <div class="pagetext">Name<span class="error-star">*</span>:</div>
                <div class="pageinput">
                    <?php $qn_name = (array_key_exists('qn_name', $this->quotation))?$this->quotation['qn_name']:"";?>
                    <input type="text" size="60" value="<?php echo $qn_name;?>" name="qn_name" id="qn_name">
                </div>
            </div>
            
            <div class="pageoverflow">
                <div class="pagetext">Customer:</div>
                <div class="pageinput">
                    <select name="cus_id" id="cus_id">
                        <option selected="" value="">-- Select Customer--</option>
                        <?php foreach ($this->customers as $_key => $_value): ?> 
                        <?php $cus_id = (array_key_exists('cus_id', $this->quotation))?$this->quotation['cus_id']:"";?>
                        <option <?php echo ($_key == $cus_id)?"selected":"";?> value="<?php echo $_key; ?>"><?php echo $_value; ?></option>
                        <?php endforeach; ?>
                    </select>
                    
                    
                    
                    &nbsp;&nbsp;&nbsp;
                    <a target="_blank" href="<?php echo $this->url(array('controller' => 'customer', 'action' => 'form'), null, TRUE) ?>">Add Customer</a>
                </div>
            </div>

            <div class="pageoverflow">
                <p class="pagetext">&nbsp;</p>
                <p class="pageinput">
                    <a id="create-user" href="#" style="text-decoration:none;">Add Product / Job</a>
                    <a id="export-calculator" href="#" style="text-decoration:none;">Export Calculator</a>
                </p>
            </div>
            
            
            <div class="pageoverflow <?php echo (count($this->quotationReference) > 0 )?"":"display-none"; ?>"  id="calculator-table">
                <div class="pagetext">Quotation Details: </div>
                <div class="pageinput">
                    <div class="table-overflow">
                    <table  style="width: 57%; margin: 0px;" class="pagetable">
                        <tbody>
                            <tr>
                                <th class='display-none' style="height: 30px;">Type</th>
                                <th style="height: 30px;">Code</th>
                                <th style="height: 30px;">Category</th>
                                <th style="height: 30px;">Sub-Category</th>
                                <th style="height: 30px;">UOM</th>
                                <th style="height: 30px;">Description</th>
                                <th style="height: 30px;">Quantity</th>
                                <th class="<?php echo ($this->user->role == "ADMIN") ? "" : "display-none"; ?>" style="height: 30px;">Cost Price (RM)</th>
                                <th style="height: 30px;">Selling Price (RM)</th>
                                <th style="height: 30px;">Edit</th>
                                <th style="height: 30px;">Delete</th>
                                <th class='display-none'>Input</th>
                            </tr>
                            <?php $k = 8000;?>
                            
                            
                            
                            <?php $totalQrefQuantity = 0;?>
                            
                            
                            
                            
                            <?php foreach($this->quotationReference as $_quotationReference): ?>
                            <?php $totalQrefQuantity += $_quotationReference['qnr_qty'];?>
                            <tr class="row2 trid<?php  echo count($this->quotationReference)+ $k;?>" trid="<?php  echo count($this->quotationReference)+ $k;?>">
                                <th class='display-none' style="height: 30px;"><?php echo $_quotationReference['qnr_type'];?></th>
                                <td><?php echo $_quotationReference['qnr_name'];?></td>
                                <td>
                                    <?php if ( count($this->allCategories) >0 ): ?>
                                    <?php if(array_key_exists($_quotationReference['qnr_cat_id'], $this->allCategories)): ?>
                                    <?php echo $this->allCategories[$_quotationReference['qnr_cat_id']]['cat_name']; ?>
                                    <?php else:?>
                                        --
                                    <?php endif; ?>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?php if ( count($this->allCategories) >0 ): ?>
                                    <?php if(array_key_exists($_quotationReference['qnr_sub_cat_id'], $this->allCategories)): ?>
                                        <?php echo $this->allCategories[$_quotationReference['qnr_sub_cat_id']]['cat_name']; ?>
                                    <?php else:?>
                                        --
                                    <?php endif; ?>
                                    <?php endif; ?>
                                </td>
                                <td><?php echo $_quotationReference['qnr_uom'];?></td>
                                <td><?php echo ($_quotationReference['qnr_description'] == '')?"&nbsp;":nl2br($_quotationReference['qnr_description']) ;?></td>
                                <td><?php echo $_quotationReference['qnr_qty'];?></td>
                                <td class="<?php echo ($this->user->role =="ADMIN")?"":"display-none"; ?>"><?php echo $_quotationReference['qnr_materialcost'];?></td>
                                <td><?php echo $_quotationReference['qnr_materialsrp'];?></td>
                                
                                <td><a href='#' class='edit_modal'>Edit</a></td>
                                <td><a href='#' class='delete_modal delete_qnrids' delete_qnrids="<?php echo $_quotationReference['qnr_id'];?>" >Delete</a></td>
                                
                                <td class='display-none hidden-table'>
                                    <input type='hidden' class='edit_type' value='<?php echo $_quotationReference['qnr_type'];?>' name='type[]'/>
                                    <input type='hidden' class='edit_product_material_code' value='<?php echo $_quotationReference['qnr_name'];?>' name='product_material_code[]'/>
                                    
                                    
                                    
                                    <input type='hidden' class='edit_category' value='<?php echo $_quotationReference['qnr_cat_id'];?>' name='category[]'/>
                                    <input type='hidden' class='edit_sub_category' value='<?php echo $_quotationReference['qnr_sub_cat_id'];?>' name='sub_category[]'/>
                                    
                                    
                                    <input type='hidden' class='edit_uom' value='<?php echo $_quotationReference['qnr_uom'];?>' name='uom[]'/>
                                    <input type='hidden' class='edit_qty' value='<?php echo $_quotationReference['qnr_qty'];?>'  name='qty[]'>
                                    <input type='hidden' class='edit_srp' value='<?php echo $_quotationReference['qnr_materialsrp'];?>' name='srp[]'/>
                                    <input type='hidden' class='edit_cost' value='<?php echo $_quotationReference['qnr_materialcost'];?>' name='cost[]'/>
                                    <input type='hidden' class='edit_totalsrp modal_srp' value='<?php echo $_quotationReference['qnr_totalmaterialsrp'];?>' name='totalsrp[]'/>
                                    <input type='hidden' class='edit_totalcost modal_cost' value='<?php echo $_quotationReference['qnr_totalmaterialcost'];?>' name='totalcost[]'/>
                                    <input type='hidden' class='edit_inventorylist' value='<?php echo $_quotationReference['qnr_ref_id'];?>' name='inventorylist[]' />
                                    <input type='hidden' class='edit_qnr_description' value='<?php echo $_quotationReference['qnr_description'];?>' name='qnr_description[]' />
                                    <input type='hidden' class='edit_qnr_id' value='<?php echo $_quotationReference['qnr_id'];?>' name='qnr_id[]' />
                                </td>    
                            </tr>
                            <?php $k++;?>
                            <?php endforeach;?>
                        </tbody></table>
                    </div>
                </div>
            </div>
            
            <div class="pageoverflow <?php echo ($this->user->role == "ADMIN") ? "" : "display-none"; ?>">
                <p class="pagetext">Total Cost Price</p>
                <p class="pageinput">
                    <?php $qn_costprice = (array_key_exists('qn_costprice', $this->quotation))?$this->quotation['qn_costprice']:"";?>
                    <input type="text" readonly size="60" id="total_cost_price" value="<?php echo $qn_costprice;?>" name="qn_costprice">
                </p>
            </div>

            <div class="pageoverflow">
                <p class="pagetext">Total Selling Price</p>
                <p class="pageinput">
                    <?php $qn_sellingprice = (array_key_exists('qn_sellingprice', $this->quotation))?$this->quotation['qn_sellingprice']:"";?>
                    <input type="text" size="60" id="total_selling_price" value="<?php echo $qn_sellingprice;?>" name="qn_sellingprice">
                </p>
            </div>
            
            <div class="pageoverflow <?php echo ($this->user->role == "ADMIN") ? "" : "display-none"; ?>">
                <p class="pagetext">Profit/Loss margin (RM)</p>
                <p class="pageinput">
                    <?php $qn_profit_loss_margin = (array_key_exists('qn_profit_loss_margin', $this->quotation))?$this->quotation['qn_profit_loss_margin']:"";?>
                    <input type="text" readonly size="60" id="profilt_loss_margin" value="<?php echo $qn_profit_loss_margin;?>" name="qn_profit_loss_margin">
                </p>
            </div>
            
            <div class="pageoverflow">
                <div class="calculator">
                    <div class="job-material-cnt">
                        <div class="cal-text-cnt"> Quotation Image</div>
                        <input id="image_id" name="qni_image[]"  class="image_class" type="file" />
                    </div>
                    <div class="job-material-cnt">
                        <div class="cal-text-cnt"> &nbsp;</div>
                        <a href="#" class="add-image"><img width="28" height="28" src="<?php echo $this->IMAGE_PATH; ?>icons/system/plus.png" alt="Edit" title="Edit" /></a>
                    </div>
                </div>
            </div>             
            
            <?php if ( count($this->quotationImages) > 0 ):?>
            <div class="pageoverflow">
                    <p class="pagetext"> Quotation Image</p>
                    <div class="pageinput">
                       <div class="project-img">
                            <ul>
                            <?php $quotationImageChunk = array_chunk($this->quotationImages, 3); ?>
                            <?php foreach ($quotationImageChunk as $_qnImages): ?>
                                    <?php foreach ($_qnImages as $_quotationImages): ?>
                                    <li>
                                        <?php
                                            $thumb_src_path = $this->PUBLIC_PATH . "upload/quotation/thumb_".$_quotationImages['qni_image'];
                                            $src_path = $this->PUBLIC_PATH . "upload/quotation/".$_quotationImages['qni_image'];
                                        ?>
                                        <div style="float:left;">
                                            <a style="text-decoration: none;" class="lightbox" href="<?php echo $src_path; ?>">
                                                <img src="<?php echo $thumb_src_path; ?>" height="150" width="150"/>&nbsp;&nbsp;
                                            </a>
                                        </div>
                                        <div style="float:left;">
                                        <a href="#" class="print-image" imagename="<?php echo $src_path;?>"><img width="28" height="28" src="<?php echo $this->IMAGE_PATH; ?>icons/system/print.png" alt="Print" title="Print" /></a>
                                        <br/>
                                        <a href="#" class="delete-image" imageid="<?php echo $_quotationImages['qni_id']; ?>">
                                                <img width="28" height="28" src="<?php echo $this->IMAGE_PATH; ?>icons/system/false.gif" alt="Delete" title="Delete" />
                                            </a>
                                        </div>
                                        <div style="float:left;">
                                        </div>
                                        <div class='clear'></div>
                                    </li>
                                    <?php endforeach; ?>
                            <?php endforeach; ?>
                            </ul>
                        </div>
                    </div>
                </div>
            <?php endif; ?>


            <div class="pageoverflow">
                <p class="pagetext">&nbsp;</p>
                <p class="pageinput">
                    <input type="submit" title="Save changes" value="Submit" name="submitbutton">
                    <input type="button" title="Print" value="Print" onclick="printSelection()" name="submitbutton">
                    <input type="reset" title="Save changes and continue to edit" value="Reset" name="apply">
                </p>
            </div>


            <div style="clear: both;"></div>
        </div>
    </form>
</div>
<div class="pop-up" id="dialog-form" title="Add Job / Product">
    <p class="validateTips">All form fields are required.</p>
    <fieldset>
        <label for="modal_type">Type</label>
        <select id="modal_type" name="modal_type" class="text">
            <option value="product">Product</option>
            <option value="job">Job</option>
        </select>
        
        <label for="modal_cat">Category</label>
        <select id="modal_cat" name="modal_cat" class="text">
            <option value="">  --Select Category-- </option>
            <?php foreach($this->categoryArray as $cat_key => $_cat):?>
                <option value="<?php echo $cat_key;?>"><?php echo $_cat;?></option>
            <?php endforeach;?>
        </select>
        
        <label for='modal_sub_cat'>Sub Category</label>
        <select id='modal_sub_cat' name='modal_sub_cat' class='text'>
            <option value=''>  -- Select Sub Category --  </option>
        </select>
        
        <label for="modal_code">Code</label>
        <input type="text" name="modal_code" id="modal_code" value="" class="text ui-widget-content ui-corner-all" />
        
        <label for="modal_code">UOM</label>
        <input type="text" name="modal_uom" readonly id="modal_uom" value="" class="text ui-widget-content ui-corner-all" />
        
        <label for="model_qty">Quantity</label>
        <input type="text" name="model_qty" id="model_qty" value="" class="text ui-widget-content ui-corner-all" />
        
        
        
        
        <div style='float:left;'>
        <div class="<?php echo ($this->user->role == "ADMIN") ? "" : "display-none"; ?>" >
        <label for="model_costprice">Cost price (RM)</label>
        <input type="text" readonly  name="model_costprice" id="model_costprice" value="" class="text ui-widget-content ui-corner-all" />
        </div>
        </div>
        
        <div style='float:left;'>
            <label for="model_sellingprice">Selling price (RM)</label>
            <input type="text" readonly  name="model_sellingprice" id="model_sellingprice" value="" class="text ui-widget-content ui-corner-all" />
        </div>
        <div class='clear'>&nbsp;</div>
        <label for="modal_desc">Description</label>
        <textarea name="item_desc[]" rows="6"  cols="38"  id="modal_desc" class="textarea ui-widget-content ui-corner-all" ></textarea>

        <input type="hidden" name="model_id" id="model_id" value="" />
        <input type="hidden" name="hdn_model_sellingprice" id="hdn_model_sellingprice" value="" />
        <input type="hidden" name="hdn_model_costprice" id="hdn_model_costprice" value="" />

    </fieldset>
</div>




<div class="pop-up" id="dialog-calculator" title="Export Calculator">
    <p class="validateTips">All form fields are required.</p>
    <fieldset>
        <label for="modal_code">Calculator name</label>
        <input type="text" name="modal_calculator" id="modal_calculator" value="" class="text ui-widget-content ui-corner-all" />
        <input type="hidden" name="modal_calculator_id" id="modal_calculator_id" value="" class="text ui-widget-content ui-corner-all" />
    </fieldset>
</div>

<p class="pageback">

    <a class="pageback" href="<?php echo $this->url(array('controller' => 'quotation', 'action' => 'list'), null, TRUE) ?>">&#171; Back to Listing</a>
</p>
<div class="clearb"></div>

<div id="image-protype" class="display-none">
    <div class="pageoverflow">
        <div class="calculator">
            <div class="job-material-cnt">
                <div class="cal-text-cnt"> Quotation Image</div>
                <input id="image_id" name="qni_image[]"  class="image_class" type="file" />
            </div>
            <div class="job-material-cnt">
                <div class="cal-text-cnt"> &nbsp;</div>
                <a href="#" class="add-image"><img width="28" height="28" src="<?php echo $this->IMAGE_PATH; ?>icons/system/plus.png" alt="Edit" title="Edit" /></a>
            </div>
            <div class="job-material-cnt">
                <div class="cal-text-cnt"> &nbsp;</div>
                <a href="#" class="remove-image"><img width="28" height="28" src="<?php echo $this->IMAGE_PATH; ?>icons/system/minus.png" alt="Edit" title="Edit" /></a>
            </div>
        </div>
    </div>             
</div>   

<div id="printContent" style='display: none;'>
    <div id="container">
        <div id="invoice_bdy">
            <div class="rep_tbldiv">
                <div class="space"></div>
                <div class="clear"></div>
                <div class="clear"></div>
                <div class="invoice_logo">
                    <div style="float:left">
                        <?php $src_path = $this->PUBLIC_PATH . "upload/company/thumb_" . $this->adminData['adm_logo']; ?>
                        <img id="loadingimage" src="<?php echo $src_path ?>" alt="logo" border="0" width="130px" height="130px"> 
                    </div>
                    <div style="float:left;padding: 15px;">
                        <?php echo $this->adminData['adm_companyname']; ?><br/>
                        <?php echo nl2br($this->adminData['adm_address']); ?><br/>
                        Phone : <?php echo $this->adminData['adm_telephone']; ?>&nbsp;&nbsp;&nbsp;Fax : <?php echo $this->adminData['adm_fax']; ?><br/>
                        Reg No: <?php echo $this->adminData['adm_registration_number']; ?>
                    </div>
                </div>
                <div class="bill_tbl">
                    <table class="tbl_data" cellpadding="0" cellspacing="0">
                        <thead>
                            <tr>
                                <th align="right">Quotation to </th>
                                <td align="left"><?php echo $this->quotation['cus_name']; ?></td>
                            </tr>
                            <tr>
                                <th align="right">Quotation number </th>
                                <td align="left">QN<?php echo str_pad($this->quotation['qn_id'], 4, "0", STR_PAD_LEFT); ?></td>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <th align="right">Quotation date </th>
                                <td align="left"><?php echo date('Y-m-d', strtotime($this->quotation["qn_created"])); ?></td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                <div class="clear"></div>
                <table class="rept_tbl" cellpadding="0" cellspacing="0" width="885">
                    <thead>
                        <tr>
                            <th width="80%">Description</th>
                            <th width="8%">Quantity</th>
                            <th width="12%">Amount</th>
                        </tr>
                    </thead> <tbody>
                        <?php foreach ($this->finalQREfArray as $_qkey => $_qref): ?>
                            <?php if (array_key_exists('data', $_qref)): ?>
                                <tr class="t-border">
                                    <td><p class="title"><?php echo $this->allCategories[$_qkey]['cat_name']; ?></p></td>
                                    <td>&nbsp;</td>
                                    <td>&nbsp;</td>
                                </tr>
                                <?php foreach ($_qref['data'] as $_value): ?>
                                    <?php foreach ($_value as $_val): ?>
                                        <tr>
                                            <td>
                                                <b>-<?php echo $_val['qnr_name']; ?></b>
                                                <?php if ($_val['qnr_description'] != ''): ?>
                                                    <ul class="discription">       
                                                        <li>
                                                            <?php echo nl2br($_val['qnr_description']); ?>
                                                        </li>
                                                    </ul>
                                                <?php endif; ?>
                                            </td>
                                            <td><?php echo $_val['qnr_qty']; ?></td>
                                            <td><?php echo $_val['qnr_materialsrp']; ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php endforeach; ?>
                            <?php elseif (array_key_exists('subcategory', $_qref)): ?>
                                <tr class="t-border">
                                    <td><p class="title"><?php echo $this->allCategories[$_qkey]['cat_name']; ?></p></td>
                                    <td>&nbsp;</td>
                                    <td>&nbsp;</td>
                                </tr>
                                <?php
                                //Extract the first key of subcategory array
                                $subCategories = array_keys($_qref['subcategory']);
                                $sub_category_key = $_qref['subcategory'][$subCategories['0']]['0']['qnr_sub_cat_id'];
                                ?>
                                <tr>
                                    <td>
                                        <b>- <?php echo $this->allCategories[$sub_category_key]['cat_name']; ?></b>
                                    </td>
                                    <td>&nbsp;</td>
                                    <td>&nbsp;</td>
                                </tr> 
                                <?php foreach ($_qref['subcategory'] as $_value): ?>
                                    <?php foreach ($_value as $_val): ?>
                                        <tr>
                                            <td><p><b><?php echo $_val['qnr_name']; ?></b></p>
                                                <?php if ($_val['qnr_description'] != ''): ?>
                                                    <ul class="discription">       
                                                        <li><?php echo nl2br($_val['qnr_description']); ?></li>
                                                    </ul>
                                                <?php endif; ?>
                                            </td>
                                            <td><?php echo $_val['qnr_qty']; ?></td>
                                            <td><?php echo $_val['qnr_materialsrp']; ?></td>
                                        </tr>  
                                    <?php endforeach; ?>
                                <?php endforeach; ?>
                            <?php else:?>
                                <tr class="t-border">
                                    <td valign="top">
                                        <p class="sub-title">
                                            <b><?php echo $_qref['qnr_name']; ?></b>
                                        </p>
                                        <?php if ($_qref['qnr_description'] != ''): ?>
                                            <ul class="discription">       
                                                <li><?php echo nl2br($_qref['qnr_description']); ?></li>
                                            </ul>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <p class="sub-title"><?php echo $_qref['qnr_qty']; ?></p>
                                    </td>
                                    <td>
                                        <p class="sub-title"><?php echo $_qref['qnr_materialsrp']; ?></p>
                                    </td>
                                </tr>
                            <?php endif; ?>
                        <?php endforeach; ?>
                        <tr class="lt-border">
                            <td valign="top">&nbsp;</td>
                            <td><p class="title qty-txt"><strong><?php echo $totalQrefQuantity;?></strong></p></td>
                            <td><p class="title amount-txt"><strong><?php echo $this->quotation['qn_sellingprice'];?></strong></p></td>
                        </tr>
                    </tbody>

                </table>
                <p> <strong>We greatly value your business. Thank you for quotation inquiry.</strong> </p>
                <div style="width:100%;border: 0px solid red;">&nbsp;
                    <div style="float:left;width:25%;border-bottom: 1px solid #aaa;">
                        <p><strong>Prepared By,<br>
                                <br>
                                <br>
                            </strong></p>
                    </div>
                    <div style="float:right;width:25%;border-bottom: 1px solid #aaa;">
                        <p><strong>Approved By,<br>
                                <br>
                                <br>
                            </strong></p>
                    </div>
                </div>
            </div>
            <br>
            <br>
            <br>
            <br>
            <!--Invoice table end here--> 
            <!--Invoice last section start here--> 
        </div>
        <!--Invoice last section end here--> 
    </div>
</div>

<div id="printContent1" style="display:none;">
    <div id="container">
        <div id="invoice_bdy">
            <div class="rep_tbldiv">
                <div class="space"></div>
                <div class="clear"></div>
                <div class="clear"></div>
                <div class="invoice_logo">
                    <div style="float:left">
                        <?php $src_path = $this->PUBLIC_PATH . "upload/company/thumb_" . $this->adminData['adm_logo']; ?>
                        <img id="loadingimage" src="<?php echo $src_path ?>" alt="logo" border="0" width="130px" height="130px"> 
                    </div>
                    <div style="float:left;padding: 15px;">
                        <?php echo $this->adminData['adm_companyname']; ?><br/>
                        <?php echo nl2br($this->adminData['adm_address']); ?><br/>
                        Phone : <?php echo $this->adminData['adm_telephone']; ?>&nbsp;&nbsp;&nbsp;Fax : <?php echo $this->adminData['adm_fax']; ?><br/>
                        Reg No: <?php echo $this->adminData['adm_registration_number']; ?>
                    </div>
                </div>
                <div class="bill_tbl">
                    <table class="tbl_data" cellpadding="0" cellspacing="0">
                        <thead>
                            <tr>
                                <th align="right">Quotation to </th>
                                <td align="left"><?php echo $this->quotation['cus_name']; ?></td>
                            </tr>
                            <tr>
                                <th align="right">Quotation number </th>
                                <td align="left">QN<?php echo str_pad($this->quotation['qn_id'], 4, "0", STR_PAD_LEFT); ?></td>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <th align="right">Quotation date </th>
                                <td align="left"><?php echo date('Y-m-d', strtotime($this->quotation["qn_created"])); ?></td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                <div class="clear"></div>
                <table class="rept_tbl" cellpadding="0" cellspacing="0" width="885">
                    <thead>
                        <tr>
                            <th width="80%">Description</th>
                            <th width="8%">Quantity</th>
                            <th width="12%">Amount</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach($this->finalQREfArray as $_qkey => $_qref):?>
                            <?php if (array_key_exists('subcategory', $_qref)): ?>
                                    <tr>
                                        <td colspan="3" valign="top">
                                            <div class="rept_tbl-rows">
                                                <div class="rept_tbl-row-desc">
                                                    <p class="title">
                                                        <?php echo $this->allCategories[$_qkey]['cat_name']; ?>
                                                    </p>
                                                    <?php foreach($_qref['subcategory'] as $_value): ?>
                                                    
                                                    <p class="sub-title">
                                                        - <b><?php echo $this->allCategories[$_value['0']['qnr_sub_cat_id']]['cat_name']; ?></b>
                                                    </p>
                                                    <?php foreach($_value as $_val): ?>
                                                    
                                                    <?php if ( count($_value) == 1 ): ?>
                                                    <p class="child-title">
                                                        <?php echo $_val['qnr_name'];?>
                                                    </p>
                                                    <?php else: ?>
                                                    <p class="child-title">
                                                        <?php echo $_val['qnr_name'];?>
                                                    </p>
                                                    <?php endif; ?>
                                                    <?php endforeach;?>
                                                    <?php endforeach;?>
                                                </div> 
                                                
                                                <div class="rept_tbl-row-qty">
                                                    <p class="title">&nbsp;</p>
                                                    <?php foreach($_qref['subcategory'] as $_value): ?>
                                                    <?php $index = 0; ?>
                                                    <?php foreach($_value as $_val): ?>
                                                    
                                                    <?php if ( count($_value) == 1 ): ?>
                                                    <p class="sub-title">&nbsp;</p>
                                                    <p class="child-title"><?php echo $_val['qnr_qty'];?></p>
                                                    <?php else: ?>
                                                    <?php if ($index == 0):?>
                                                    <br/><br/>
                                                    <?php endif; ?>
                                                    <p class="child-title"><?php echo $_val['qnr_qty'];?></p>
                                                    <?php endif; ?>
                                                    
                                                    <?php $index++; ?>
                                                    <?php endforeach;?>
                                                    <?php endforeach;?>
                                                </div>
                                                
                                                <div class="rept_tbl-row-amount">
                                                    <p class="title">&nbsp;</p>
                                                    <?php foreach($_qref['subcategory'] as $_value): ?>
                                                    <?php $index = 0; ?>
                                                    <?php foreach($_value as $_val): ?>
                                                    <?php if ( count($_value) == 1 ): ?>
                                                    <p class="sub-title">&nbsp;</p>
                                                    <p class="child-title"><?php echo $_val['qnr_materialsrp'];?></p>
                                                    <?php else:?>
                                                    <?php if ($index == 0):?>
                                                    <br/><br/>
                                                    <?php endif; ?>
                                                    <p class="child-title"><?php echo $_val['qnr_materialsrp'];?></p>
                                                    <?php endif; ?>
                                                    <?php $index++; ?>
                                                    <?php endforeach;?>
                                                    <?php endforeach;?>
                                                </div>
                                            </div>         
                                        </td>
                                    </tr>
                            <?php elseif (array_key_exists('data', $_qref)): ?>
                                    <tr>
                                        <td colspan="3" valign="top">
                                            <div class="rept_tbl-rows">
                                                <div class="rept_tbl-row-desc">
                                                    <p class="title">
                                                        <?php echo $this->allCategories[$_qkey]['cat_name']; ?>
                                                    </p>
                                                    <?php foreach($_qref['data'] as $_value): ?>
                                                    <?php foreach($_value as $_val): ?>
                                                    
                                                    <p class="child-title">
                                                        -<b><?php echo $_val['qnr_name'];?></b>
                                                    </p>
                                                    <p class="child-title">
                                                        -<?php echo nl2br(  $_val['qnr_description']);?>
                                                    </p>
                                                    <?php endforeach;?>
                                                    <?php endforeach;?>
                                                </div> 
                                                
                                                <div class="rept_tbl-row-qty">
                                                    <p class="title">&nbsp;</p>
                                                    <?php foreach($_qref['data'] as $_value): ?>
                                                    <?php foreach($_value as $_val): ?>
                                                    <p class="child-title"><?php echo $_val['qnr_qty'];?></p>
                                                    <?php endforeach;?>
                                                    <?php endforeach;?>
                                                </div>
                                                
                                                <div class="rept_tbl-row-amount">
                                                    <p class="title">&nbsp;</p>
                                                    <?php foreach($_qref['data'] as $_value): ?>
                                                    <?php foreach($_value as $_val): ?>
                                                    <p class="child-title"><?php echo $_val['qnr_materialsrp'];?></p>
                                                    <?php endforeach;?>
                                                    <?php endforeach;?>
                                                </div>
                                            </div>         
                                        </td>
                                    </tr>
                            <?php else : ?>
                        <tr>
                            <td colspan="3" valign="top">
                                <div class="rept_tbl-rows">
                                    <div class="rept_tbl-row-desc">
                                        <p class="sub-title">
                                            <b><?php echo $_qref['qnr_name']; ?></b>
                                        </p>
                                    </div>
                                    <div class="rept_tbl-row-qty">
                                        <p class="sub-title"><?php echo $_qref['qnr_qty']; ?></p>
                                    </div>
                                    <div class="rept_tbl-row-amount">
                                        <p class="sub-title"><?php echo $_qref['qnr_materialsrp']; ?></p>
                                    </div>
                                </div> 
                            </td>
                        </tr> 
                            <?php endif; ?>
                        <?php endforeach;?>
                        <tr>
                            <td colspan="3" valign="top">
                                <div class="rept_tbl-rows">
                                    <div class="rept_tbl-row-desc">
                                        <p class="title">&nbsp;</p>
                                    </div>
                                    <div class="rept_tbl-row-qty">
                                        <p class="title qty-txt"><strong><?php echo $totalQrefQuantity;?></strong></p>
                                    </div>
                                    <div class="rept_tbl-row-amount">
                                        <p class="title amount-txt"><strong><?php echo $this->quotation['qn_sellingprice'];?></strong></p>                         
                                    </div>
                                </div> 
                            </td>
                        </tr>
                    </tbody>
                </table>
                <p> <strong>We greatly value your business. Thank you for quotation inquiry.</strong> </p>
                <div style="width:100%;border: 0px solid red;">&nbsp;
                    <div style="float:left;width:25%;border-bottom: 1px solid #aaa;">
                        <p><strong>Prepared By,<br>
                                <br>
                                <br>
                            </strong></p>
                    </div>
                    <div style="float:right;width:25%;border-bottom: 1px solid #aaa;">
                        <p><strong>Approved By,<br>
                                <br>
                                <br>
                            </strong></p>
                    </div>
                </div>
            </div>
            <br>
            <br>
            <br>
            <br>
            <!--Invoice table end here-->
            <!--Invoice last section start here-->
        </div>
        <!--Invoice last section end here-->
    </div>

</div>


<script>

$(function() {

    //Variable Initialization
    var modal_type = $("#modal_type"),
            modal_code = $("#modal_code"),
            modal_uom = $("#modal_uom"),
            model_qty = $("#model_qty"),
            model_sellingprice = $("#model_sellingprice"),
            model_costprice = $("#model_costprice"),
            modal_desc = $("#modal_desc"),
            model_id = $("#model_id"),
            hdn_model_sellingprice = $("#hdn_model_sellingprice"),
            hdn_model_costprice = $("#hdn_model_costprice"),
            allFields = $([]).add(modal_type).add(modal_code).add(modal_uom).add(model_qty).add(model_sellingprice).add(model_costprice).add(model_id).add(hdn_model_sellingprice).add(hdn_model_costprice).add(modal_desc),
            tips = $(".validateTips");

    var modal_calculator = $("#modal_calculator");
    var modal_calculator_id  = $("#modal_calculator_id ");
    var calFields = $([]).add(modal_calculator).add(modal_calculator_id);
    var calculatorItem = {};       
    
    function nl2br (str, is_xhtml) {
        var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
        return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
    }
    
     //Event Register of the Selling Price 
    $('#total_selling_price').on('keyup focusout blur', function() {

        //Validation for the Total Selling price as number
        var totalSellingprice = $('#total_selling_price').val();
        totalSellingprice = jQuery.trim(totalSellingprice);
        var numberPattern = /^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/;
        numberResult = numberPattern.test(totalSellingprice);
        if (numberResult === false) {
            return false;
        } else if ($('#total_cost_price').val() === '' ) {
            return false;
        } else {
            calculateTotalProfitLoss();
        }

    });  
    
    
    function getsubcategory( category, selected_category ) {
        var cat = category;
        var postData = {};
        postData['cat_parentid'] = cat;
        postData['cat_selected'] = selected_category;
        $.ajax({
            url: BASE_PATH + '/quotation/getsubcategory',
            type: 'POST',
            data: postData,
            success: function(response) {
                $('#modal_sub_cat').html(response);
            }
        });
    }
    
    $('#modal_cat').change( function(){
       var cat = $(this).val();
       var selected_category = '';
       getsubcategory(cat, selected_category);
    });
    

    //Form Validation
    $('#quotation-form').submit(function() {
        $('.jscript-error-container').html('');
        //Remove the error class
        $("#quotation-form :input").removeClass('error');

        //Hide Error Container and remove the contents from it
        $('.jscript-error-container').html('');
        $('.jscript-error-container').hide();

        //Initialize error container
        var errMessage = [];
        /*
        var name = $('#qn_name').val();
        name = jQuery.trim(name);
        if (name === '') {
            errMessage.push('Please enter quotation name');
            $('#qn_name').addClass('error');
            $('#calculator_name').focus();
        }
        */

        var item_count = $('#item_count').val();
        item_count = parseInt(item_count);
        if (item_count <= 0) {
            errMessage.push('Please add atleast one product or job');
        }

        //Validation for the Total Selling price as integer
        var totalSellingprice = $('#total_selling_price').val();
        totalSellingprice = jQuery.trim(totalSellingprice);
        var numberPattern = /^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/;
        numberResult = numberPattern.test(totalSellingprice);
        if (numberResult === false) {
            errMessage.push('Please enter valid selling price');
            $('#total_selling_price').addClass('error');
            $('#total_selling_price').focus();
        }

        //Image validation
        var imageCounter = 0;
        $('#quotation-form').find('.image_class').each(function() {
            if ($(this).val() !== '' ) {
                var ext = $(this).val().split('.').pop().toLowerCase();
                if($.inArray(ext, ['gif','png','jpg','jpeg']) === -1) {
                    $(this).addClass('error');
                    $(this).focus();
                    imageCounter++;
                }

            }
        });
        if (imageCounter > 0) {
            errMessage.push('Please select image with valid extension');
        }

        if (errMessage.length > 0) {
            var content = "";
            $.each(errMessage, function(index,value){
                content += "<div class='pageoverflow'><label class='errorlabel'>"+value+"</label></div>";
            });
            $('.jscript-error-container').html(content);
            $('.jscript-error-container').show();
            return false;
        } else {
            return true;
        }

    });
    
    
    //On change of the Modal type in the Modal box this hidden modal id is set to blank for validation purpose
    $('#modal_type').change(function(){
        $('#model_id').val('');
    });

    //Validation of the calculator
    function checkCalculatorValid(o) {
        var model_cal_id = $('#modal_calculator_id').val();
        if ((model_cal_id  === "") || (typeof model_cal_id  === "undefined")) {
            o.addClass("ui-state-error");
            updateTips("Please enter calculator");
            return false;
        } else {
            return true;
        }
    }

    //Event Register of the Quantity in the Modal Box
    $('#model_qty').on('keyup focusout blur', function() {
        checkQuantityValid(model_qty);
    });

    //Update and animation show of error in the modal box fields
    function updateTips(t) {
        tips.text(t).addClass("ui-state-highlight");
        setTimeout(function() {
            tips.removeClass("ui-state-highlight", 1500);
        }, 700);
    }

    //Calculate final cost price
    function calculateTotalModalCostPrice() {
        var costprice = 0.00;
        $('.modal_cost').each(function() {
            if (jQuery.trim($(this).val()) !== '') {
                costprice += parseFloat(jQuery.trim($(this).val()));
            }
        });
        $('#total_cost_price').val(costprice.toFixed(2));
    }

    //Calculate profit and loss margin
    function calculateTotalProfitLoss() {
        var profilt_loss_margin = 0.00;
        var sellingPrice = parseFloat(jQuery.trim($('#total_selling_price').val())).toFixed(2);
        var costPrice = parseFloat(jQuery.trim($('#total_cost_price').val())).toFixed(2);
        profilt_loss_margin = sellingPrice - costPrice;
        profilt_loss_margin = profilt_loss_margin.toFixed(2);
        $('#profilt_loss_margin').val(profilt_loss_margin);
    }

    //Calculate final selling price
    function calculateTotalModalSellingPrice() {
        var sellingprice = 0.00;
        $('.modal_srp').each(function() {
            if (jQuery.trim($(this).val()) !== '') {
                sellingprice += parseFloat(jQuery.trim($(this).val()));
            }
        });
        $('#total_selling_price').val(sellingprice.toFixed(2));
    }


    //Validation of the Quantity
    function checkQuantityValid(o) {
        var model_qty = $('#model_qty').val();
        //Validation for the Quantity as integer
        var pattern = /^\d+$/;
        result = pattern.test(model_qty);
        if (result === false) {
            o.addClass("ui-state-error");
            updateTips("Quantity should be a number only");
            return false;
        } else if ($('#model_id').val() === ''){
            o.addClass("ui-state-error");
            updateTips("Please enter product or item code before quantity");
            return false;
        } else {
            model_qty = jQuery.trim(model_qty);
            var quantity = parseInt(model_qty);

            var costPrice = $('#hdn_model_costprice').val();
            costPrice = parseFloat(jQuery.trim(costPrice)).toFixed(2);

            var sellingprice = $('#hdn_model_sellingprice').val();
            sellingprice = parseFloat(jQuery.trim(sellingprice)).toFixed(2);

            var totalCost = quantity * costPrice;
            var totalSrp = quantity * sellingprice;

            $('#model_costprice').val(totalCost.toFixed(2));
            $('#model_sellingprice').val(totalSrp.toFixed(2));
            return true;
        }
    }

    //Validation of the product
    function checkProductItemValid(o) {
        var model_id = $('#model_id').val();
        if ((model_id === "") || (typeof model_id === "undefined")) {
            o.addClass("ui-state-error");
            updateTips("Please enter atleast one product or item code");
            return false;
        } else {
            return true;
        }
    }
    //Event registration for the button 
    $( "#create-user" ).button();
    $( "#export-calculator" ).button();

    //Event registration for the dialog open
    $( "#create-user" ).click(function() {
        
        
    var Linkobj = {};
            Linkobj['type'] = 'add';
            Linkobj['trid'] = '';
            Linkobj['qnr_id'] = '';
            $( "#dialog-form" ).dialog({ title: "Add Job / Product" });
            $( "#dialog-form" ).data('link', Linkobj) 
                    .dialog( "open" );  
            
    });

    $( "#export-calculator" ).click(function() {
        $( "#dialog-calculator" ).dialog( "open" );
    });
    var deleteQnrIdArray = [];
    //Event registration for the delete of the job and products
    $('body').delegate('.delete_modal', 'click', function() {
        
        //If the delete is done with the existing than quotation reference than delete id are added in the hidden variable
        if ($(this).hasClass('delete_qnrids')) {
            deleteQnrIdArray.push($(this).attr('delete_qnrids'));
            $('#hdn_delete_qnrids').val(deleteQnrIdArray.toString());
        }
        
        
        $(this).parents('tr').remove();

        //Calculate final srp and cost price
        calculateTotalModalCostPrice();
        calculateTotalModalSellingPrice();
        calculateTotalProfitLoss();

        //Substract the itemcount to 1 once table row is added
        var item_count  = $('#item_count').val();
        item_count = parseInt(item_count);
        if (item_count > 0 ) {
            item_count = parseInt(item_count) - 1;
            $('#item_count').val(item_count);
        }
        //Hide the blank table header
        if (item_count === 0) {
            $('#calculator-table').hide();
        }
        return false;

    });


    //Event registration for the dialog box
    $("#dialog-calculator").dialog({
    autoOpen: false,
        height: 270,
        width: 370,
        modal: true,
        buttons: {
            "Add": function() {

                //Bool to check the fields validation of the modal box
                    var bValid = true;
                    //Remove all error form the modal box
                    calFields.removeClass("ui-state-error");

                    //Validation of the modal fields
                    bValid = bValid && checkCalculatorValid(modal_calculator);
                    if (bValid) {
                        $.each(calculatorItem, function(index, obj) {
                            //Show the table
                            $('#calculator-table').removeClass('display-none');
                            
                            //Add the itemcount to 1 once table row is added
                            var item_count = $('#item_count').val();
                            item_count = parseInt(item_count) + 1;
                            $('#item_count').val(item_count);
                            
                            var classtrid = "trid" + item_count;
                            
                            var ucFirsttype = obj.calr_type.charAt(0).toUpperCase() + obj.calr_type.slice(1);
                            
                            
                            //Append the tr to the table
                            var classAdmin = '<?php echo ($this->user->role == "ADMIN") ? "" : "display-none"; ?>';
                            var tdRow = "<td class='display-none'>" + ucFirsttype + "</td>" +
                            "<td>" + obj.calr_name + "</td>" +
                            "<td>--</td>" +
                            "<td>--</td>" +
                            "<td>" + obj.calr_uom + "</td>" +
                            "<td>&nbsp;</td>" +
                            "<td>" + obj.calr_qty + "</td>" +
                            "<td class='" + classAdmin + "' >" + obj.calr_materialcost + "</td>" +
                            "<td>" + obj.calr_materialsrp + "</td>" +
                            "<td><a href='#' class='edit_modal'>Edit</a></td>" +
                            "<td><a href='#' class='delete_modal'>Delete</a></td>" +
                            "<td class='display-none hidden-table'>" +
                            "<input type='hidden' class='edit_type' value='" + obj.calr_type + "' name='type[]'/>" +
                            "<input type='hidden' class='edit_product_material_code' value='" + obj.calr_name + "' name='product_material_code[]'/>" +
                            "<input type='hidden' class='edit_category' value='' name='category[]'/>" +
                            "<input type='hidden' class='edit_sub_category' value='' name='sub_category[]'/>" +
                            "<input type='hidden' class='edit_uom' value='" + obj.calr_uom + "' name='uom[]'/>" +
                            "<input type='hidden' class='edit_qty' value='" + obj.calr_qty + "'  name='qty[]'>" +
                            "<input type='hidden' class='edit_srp' value='" + obj.calr_materialsrp + "' name='srp[]'/>" +
                            "<input type='hidden' class='edit_cost' value='" + obj.calr_materialcost + "' name='cost[]'/>" +
                            "<input type='hidden' value='" + obj.calr_totalmaterialsrp + "' class='edit_totalsrp modal_srp' name='totalsrp[]'/>" +
                            "<input type='hidden' value='" + obj.calr_totalmaterialcost + "' class='edit_totalcost modal_cost' name='totalcost[]'/>" +
                            "<input type='hidden' value='" + obj.calr_ref_id + "' class='edit_inventorylist' name='inventorylist[]' />" +
                            "<input type='hidden' value='' class='edit_qnr_description' name='qnr_description[]' />" +
                            "<input type='hidden' value='' class='edit_qnr_id' name='qnr_id[]' />" +
                            "</td>";
                            var trRow = "<tr class='row2 "+classtrid+"' trid="+item_count +" >" + tdRow + "</tr>";
                            $(".pagetable").append(trRow);

                            //Calculate the final srp and cost price   
                            calculateTotalModalSellingPrice();
                            calculateTotalModalCostPrice();

                            //Calculate the profit
                            calculateTotalProfitLoss();
                             
                            //Show the table
                            $('#calculator-table').show();
                             
                        });
                        $(this).dialog("close");
                    }
                },
                Cancel: function() {
                    $(this).dialog("close");
                }
            },
            close: function() {
                calFields.val("").removeClass("ui-state-error");
            }
        });
        
        
        $('body').delegate('.edit_modal', 'click', function() {
            var content = $(this);
            var obj = $(content.parents('tr').find('.hidden-table'));
            var editTrId = content.parents('tr').attr('trid');
            var edit_type = obj.find('.edit_type').val();
            var edit_product_material_code =obj.find('.edit_product_material_code').val();
            var edit_uom = obj.find('.edit_uom').val();
            var edit_qty = obj.find('.edit_qty').val();
            var edit_srp = obj.find('.edit_srp').val();
            var edit_cost = obj.find('.edit_cost').val();
            var edit_totalsrp = obj.find('.edit_totalsrp').val();
            var edit_totalcost = obj.find('.edit_totalcost').val();
            var edit_inventorylist = obj.find('.edit_inventorylist').val();
            var edit_qnr_description = obj.find('.edit_qnr_description').val();
            var edit_qnr_id = obj.find('.edit_qnr_id').val();
            $('#modal_type').val(edit_type);
            $('#modal_code').val(edit_product_material_code);
            $('#modal_uom').val(edit_uom);
            
            
            
            //Fetch the Category and Sub Category
            var edit_category = obj.find('.edit_category').val();
            var edit_sub_category = obj.find('.edit_sub_category').val();
            
            //Set the Cateogry Value
            $('#modal_cat').val(edit_category);
            if (edit_category === '') {
                $('#modal_sub_cat').val('');
            } else {
                //If Sub Category is selected than make a call to Ajax and get the sub category selected
                getsubcategory(edit_category, edit_sub_category);
            }
            
            $('#model_qty').val(edit_qty);
            $('#model_costprice').val(edit_totalcost);
            $('#model_sellingprice').val(edit_totalsrp);
            $('#modal_desc').val(edit_qnr_description);
            $('#model_id').val(edit_inventorylist);
            $('#hdn_model_sellingprice').val(edit_srp);
            $('#hdn_model_costprice').val(edit_cost);
            var Linkobj = {};
            Linkobj['type'] = 'edit';
            Linkobj['trid'] = editTrId;
            Linkobj['qnr_id'] = edit_qnr_id;
            $( "#dialog-form" ).dialog({ title: "Edit Job / Product" });
            $( "#dialog-form" ).data('link', Linkobj).dialog( "open" );
        });
        
        //Event registration for the dialog box
        $("#dialog-form").dialog({
            autoOpen: false,
            height: 590,
            width: 380,
            modal: true,
            buttons: {
                "Add": function() {
                    
                    //Bool to check the fields validation of the modal box
                    var bValid = true;
                    //Remove all error form the modal box
                    allFields.removeClass("ui-state-error");

                    //Validation of the modal fields
                    bValid = bValid && checkProductItemValid(modal_code);
                    bValid = bValid && checkQuantityValid(model_qty);

                    if (bValid) {
                        //Show the table
                        $('#calculator-table').removeClass('display-none');
                        var ucFirsttype = modal_type.val().charAt(0).toUpperCase() + modal_type.val().slice(1);
                        //Append the tr to the table

                        var classAdmin = '<?php echo ($this->user->role == "ADMIN") ? "" : "display-none"; ?>';
                            
                        var path = $(this).data('link'); 
                        var qnr_idTd  = '';
                        if (path.type === 'add') {
                            //Add the itemcount to 1 once table row is added
                            var item_count = $('#item_count').val();
                            item_count = parseInt(item_count) + 1;
                            $('#item_count').val(item_count);
                            qnr_idTd = "<input type='hidden' class='edit_qnr_id' value='' name='qnr_id[]' />";
                        }
                        
                        qnr_idTd = "<input type='hidden' class='edit_qnr_id' value='" + path.qnr_id + "' name='qnr_id[]' />";
                          
                        var classtrid = "trid" + item_count;
                        
                        //Category and Sub Category 
                        var modal_cat = $('#modal_cat').val();
                        var modal_sub_cat = $('#modal_sub_cat').val();
                        
                        //Sub Category and Category text
                        var modal_cat_text = '';
                        var modal_sub_cat_text = '';
                        
                        //Validation if category is not blank than select option text
                        if (modal_cat === "") {
                            modal_cat_text = '--';
                        } else {
                            modal_cat_text = $('#modal_cat option:selected').text();
                        }
                        
                        //Validation if category is not blank than select option text
                        if (modal_sub_cat === "") {
                            modal_sub_cat_text = '--';
                        } else {
                            modal_sub_cat_text = $('#modal_sub_cat option:selected').text();
                        }
                        
                        var tdRow =  "<td class='display-none'>" + ucFirsttype + "</td>" +
                                "<td>" + modal_code.val() + "</td>" +
                                "<td>" + modal_cat_text + "</td>" +
                                "<td>" + modal_sub_cat_text + "</td>" +
                                "<td>" + modal_uom.val() + "</td>" +
                                "<td>" + nl2br(modal_desc.val()) + "</td>" +
                                "<td>" + model_qty.val() + "</td>" +
                                "<td class='" + classAdmin + "' >" + hdn_model_costprice.val() + "</td>" +
                                "<td>" + hdn_model_sellingprice.val() + "</td>" +
                                "<td><a href='#' class='edit_modal'>Edit</a></td>" +
                                "<td><a href='#' class='delete_modal'>Delete</a></td>" +
                                "<td class='display-none hidden-table'>" +
                                "<input type='hidden' class='edit_type' value='" + modal_type.val() + "' name='type[]'/>" +
                                "<input type='hidden' class='edit_product_material_code' value='" + modal_code.val() + "' name='product_material_code[]'/>" +
                                "<input type='hidden' class='edit_category' value='" + modal_cat + "' name='category[]'/>" +
                                "<input type='hidden' class='edit_sub_category' value='" + modal_sub_cat + "' name='sub_category[]'/>" +
                                "<input type='hidden' class='edit_uom' value='" + modal_uom.val() + "' name='uom[]'/>" +
                                "<input type='hidden' class='edit_qty' value='" + model_qty.val() + "'  name='qty[]'>" +
                                "<input type='hidden' class='edit_srp' value='" + hdn_model_sellingprice.val() + "' name='srp[]'/>" +
                                "<input type='hidden' class='edit_cost' value='" + hdn_model_costprice.val() + "' name='cost[]'/>" +
                                "<input type='hidden' class='edit_totalsrp modal_srp' value='" + model_sellingprice.val() + "' name='totalsrp[]'/>" +
                                "<input type='hidden' class='edit_totalcost modal_cost' value='" + model_costprice.val() + "' name='totalcost[]'/>" +
                                "<input type='hidden' class='edit_inventorylist' value='" + model_id.val() + "' name='inventorylist[]' />" +
                                "<input type='hidden' class='edit_qnr_description' value='" + modal_desc.val() + "' name='qnr_description[]' />" +
                                    qnr_idTd + 
                                "</td>";
                        
                        var trRow = "<tr class='row2 "+classtrid+"' trid="+item_count +" >" + tdRow + "</tr>";
                                
                        if (path.type === 'edit') {
                            var trid = path.trid;
                            var tableId = 'trid'+ trid;
                            $('.'+ tableId).html('');
                            $('.'+ tableId).html(tdRow);
                        } else {
                            $(".pagetable").append(trRow);
                        }

                        //Calculate the final srp and cost price   
                        calculateTotalModalSellingPrice();
                        calculateTotalModalCostPrice();

                        //Calculate the profit
                        calculateTotalProfitLoss();
                        
                        
                        //Show the table
                        $('#calculator-table').show();
                        
                        $(this).dialog("close");
                    }
                },
                Cancel: function() {
                    $(this).dialog("close");
                }
            },
            close: function() {
                allFields.val("").removeClass("ui-state-error");
                
                //Blank the category on close of the modal box
                $('#modal_cat').val('');
                
                //Blank the sub-category on close of the modal box
                $('#modal_sub_cat').html('<option value="">  -- Select Sub Category --  </option>');
                $('#modal_sub_cat').val('');
            }
        });

        //Initialization of the autocomplete for modal calculator
        jQuery("#modal_calculator").autocomplete({
            source: function(request, response) {
                var postData = {};
                postData['search'] = request.term;
                $.ajax({
                    url: BASE_PATH + '/calculator/generatecalculatosearch',
                    dataType: "json",
                    type: 'POST',
                    data: postData,
                    success: function(data) {
                        response(
                                $.map(data, function(item) {
                            return {
                                id: item.id,
                                label: item.name,
                                value: item.name,
                                uom: item.uom,
                                cost_price: item.costprice,
                                srp_price: item.srpprice,
                                cal_reference: item.CALCULATOR_REFERENCE
                            };
                        })
                                );
                    }
                });
            },
            select: function(event, ui) {
                if (ui.item.cal_reference.length >= 0) {
                    calculatorItem = ui.item.cal_reference;
                }
                $('#modal_calculator_id').val(ui.item.id);
                /*
                 $('#model_qty').val('1');
                 $('modal_code').val(ui.item.code);
                 $('#model_costprice').val(ui.item.cost_price);
                 $('#model_sellingprice').val(ui.item.srp_price);

                 $('#hdn_model_costprice').val(ui.item.cost_price);
                 $('#hdn_model_sellingprice').val(ui.item.srp_price);
                 */
            },
            minLength: 1
        });

        //Initialization of the autocomplete 
        jQuery("#modal_code").autocomplete({
            source: function(request, response) {
                var postData = {};
                postData['search'] = request.term;
                postData['type'] = $("#modal_type").val();
                $.ajax({
                    url: BASE_PATH + '/quotation/generateproductsearch',
                    dataType: "json",
                    type: 'POST',
                    data: postData,
                    success: function(data) {
                        response(
                                $.map(data, function(item) {
                            return {
                                id: item.id,
                                label: item.code,
                                uom: item.uom,
                                value: item.code,
                                cost_price: item.costprice,
                                srp_price: item.srpprice
                            };
                        })
                                );
                    }
                });
            },
            select: function(event, ui) {
                $('#model_qty').val('1');
                $('#modal_code').val(ui.item.code);
                $('#modal_uom').val(ui.item.uom);
                $('#model_costprice').val(ui.item.cost_price);
                $('#model_sellingprice').val(ui.item.srp_price);
                $('#model_id').val(ui.item.id);
                $('#hdn_model_costprice').val(ui.item.cost_price);
                $('#hdn_model_sellingprice').val(ui.item.srp_price);
            },
            minLength: 1
        });
        
        
        
        //Print Functions
        $('.print-image').click(function (){
            imagename = $(this).attr('imagename');
            var content = "<img src='"+ imagename +"'>";
            var printscript = unescape("%3Cscript%3E function printscreen(){setTimeout('timeprint()',500)} function timeprint(){ window.print();}%3C/script%3E");
            content = content + printscript;
            var pwin = window.open('', 'print_content');
            pwin.document.open();
            pwin.document.write('<html><head></head><body onload="printscreen();">' + content + '</body></html>');
            // setTimeout(pwin.print(),3000);
            pwin.document.close();
        });

});

function printSelection() {
        var content = document.getElementById("printContent").innerHTML;
        var printscript = unescape("%3Cscript%3E function printscreen(){setTimeout('timeprint()',500)} function timeprint(){ window.print();}%3C/script%3E");
        content = content + printscript;
        var pwin = window.open('', 'print_content');
        pwin.document.open();
        
        pwin.document.write('<html><head><link type="text/css" rel="stylesheet" href="<?php echo $this->CSS_PATH."quotation.css";?>" media="screen"/><link type="text/css" rel="stylesheet" href="<?php echo $this->CSS_PATH."quotation.css";?>" media="print"/></head><body onload="printscreen();">' + content + '</body></html>');
        // setTimeout(pwin.print(),3000);

        pwin.document.close();

    }        

</script>